package com.teddy.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;

import com.teddy.view.BaseGUI;

public class FileManager {
	
	public static String readFile(String path){
		return "";
	}
	
	public static String getFileName(String uri, String extension){
		File f = new File(uri);
		return f.getName().replace(extension, "");
	}
	
	public static void writeFile(String path, String content){
		try{
			FileWriter fstream = new FileWriter(path);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content);
			out.close();
		}catch (Exception e){
			     System.err.println("Error: " + e.getMessage());
		}
	}
	
	public static String buildPath(String... args){
		String path = "";
		for (String s : args){
			path+=s + "/";
		}
		path = path.replaceAll("\\\\+", "/");
		return path.substring(0, path.length() - 1);
	}
	
	public static String read(InputStream is) throws IOException{
		StringBuffer out = new StringBuffer();
	    byte[] b = new byte[4096];
	    for (int n; (n = is.read(b)) != -1;) {
	        out.append(new String(b, 0, n));
	    }
	    return out.toString();
	}
	
	public static void writeFile(String uri, InputStream is) throws IOException{
		writeFile(uri, read(is));
	}
	
	public static String convertStreamToString(InputStream is) throws Exception {
	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();
	    String line = null;
	    while ((line = reader.readLine()) != null) {
	      sb.append(line + "\n");
	    }
	    is.close();
	    return sb.toString();
	  }
	
	
	public static Image getImage( String imageResourceString ) {
		InputStream sourceStream = BaseGUI.class.getResourceAsStream( imageResourceString );
		ImageData source = new ImageData(sourceStream);
		ImageData mask = source.getTransparencyMask();
		Image image = new Image(null, source, mask);
		try {
			sourceStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}
}
